package com.leixiaoqiao.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtil {
    private static final SqlSessionFactory sqlSessionFactory;


    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();

    static{
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取SqlSessionFactory对象
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    }


    /*
      用于获取SqlSession对象
     */
    public static SqlSession getSession(){
        SqlSession sqlSession = tl.get();//通过本地线程获取SqlSession对象
        if(sqlSession == null){
            //本地线程中没有SQLSession对象
            sqlSession  = sqlSessionFactory.openSession();
            tl.set(sqlSession);
        }

        return sqlSession;
    }

    /*
     提交事务/释放资源
     */
    public static void close(){
        SqlSession sqlSession = tl.get();
        if(sqlSession != null){
            sqlSession.commit();
            sqlSession.close();
            tl.remove();
        }
    }
    /*
     回滚事务
     */
    public static void rollBack(){
        SqlSession sqlSession = tl.get();
        if(sqlSession != null){
            sqlSession.rollback();
            sqlSession.close();
            tl.remove();
        }
    }
}
